package com.superlight.designer.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.superlight.designer.comm.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Objects;
import java.util.UUID;

/**文件上传
 *
 */
@Api(value = "文件上传服务",description = "文件上传服务 API", position = 100, protocols = "http",tags = "文件上传服务")
@RequestMapping("files")
@Controller
public class FilesController {
    @Value("${custom.filepath.basePath}")
    private String basePath;

    @Value("${custom.filepath.disk}")
    private String disk;


    /**
     * 实现文件上传
     */
    @PostMapping(value = "fileUpload")
    @ResponseBody
    @ApiOperation(
            value = "文件上传"
    )
    public R<JSONObject> fileUpload(@RequestParam("file") MultipartFile file, @RequestParam String fileName, @RequestParam String filePath) {
        if (file.isEmpty()) {
            return R.failed("没有检查到文件");
        }
        String originalFilename = file.getOriginalFilename();
        fileName = UUID.randomUUID().toString().concat(originalFilename);
        int size = (int) file.getSize();

        String suffix = "/" + filePath;

        // 文件存放路径
        String directory = disk + basePath + filePath;
        String filepath = directory + "/" + fileName;
        String _filepath = basePath + filePath + "/" + fileName;

        File dest = new File(filepath);
        File dir = new File(directory);
        if (!dir.exists()) { //判断文件父目录是否存在
            boolean mkdirs = dir.mkdirs();
            if (!mkdirs) {
                return R.failed("文件目录创建失败！");
            }
        }
        try {
            file.transferTo(dest); //保存文件
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("fileName", fileName);
            jsonObject.put("filePath", _filepath);
            String suffix2 = (Objects.isNull(basePath) || basePath.length() <= 0) ? filePath.endsWith("/") || filePath.endsWith("\\/") ? filePath : filePath + "\\" : "";
            jsonObject.put("url",  "/" + suffix2 + fileName);
            jsonObject.put("size", size);
            return R.ok(jsonObject, "文件上传成功");
        } catch (IllegalStateException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return R.failed(e.getMessage());
        }
    }

}
